﻿using System;
using System.Collections.Generic;

namespace SharpTag.ID3
{
    /// <summary>
    /// Concrete implementation of the <see cref="AbstractFrameFactory"/> class.
    /// </summary>
    public class ID3FrameFactory : AbstractFrameFactory
    {
        /// <summary>
        /// Parses raw frames bytes into a Generic collection of <see cref="IFrame"/> objects.
        /// </summary>
        /// <param name="frameBytes"></param>
        /// <returns>A generic list of <see cref="IFrame"/> objects.</returns>
        public override List<IFrame> ParseID3TagFrames(byte[] frameBytes)
        {
            var offset = 0;
            byte[] workingHeader = new byte[10];
            List<IFrame> frames = new List<IFrame>();
            
            while (offset < frameBytes.Length)
            {
                Array.Copy(frameBytes, offset, workingHeader, 0, 10);
                var header = new ID3V2TagFrameHeader(workingHeader);
                if (header.Name == "\0\0\0\0")
                    break;
                var workingFrameBytes = new byte[header.Size + 10];
                Array.Copy(frameBytes, offset, workingFrameBytes, 0, workingFrameBytes.Length);
                var frame = new ID3V2TagFrame();
                frame.ParseFrameData(workingFrameBytes);
                frames.Add(frame);
                offset += workingFrameBytes.Length;
            }

            return frames;
        }

        /// <summary>
        /// Creates a new empty <see cref="IFrame"/> object.
        /// </summary>
        /// <returns>An empty <see cref="IFrame"/> object</returns>
        public override IFrame CreateID3TagFrame()
        {
            return new ID3V2TagFrame();
        }
    }
}
